package servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.UserManagerRemote;

public class ElencoUtentiServlet extends HttpServlet {

    public ElencoUtentiServlet() {
        super();
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.println("<html><title>Users</title>" +
				"<body><h1>Users</h1>");

		try {
				Hashtable<String,String> env = new Hashtable<String,String>();
				env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
				env.put(Context.PROVIDER_URL,"localhost:1099");
				InitialContext jndiContext = new InitialContext(env);
				Object ref = jndiContext.lookup("UserManager/remote");
				UserManagerRemote r = (UserManagerRemote) ref;

	
				
				List<String> utenti=r.getUsernames();
				if(utenti.isEmpty())
				{
					out.println("Non sono presenti utenti");
				}
				else
				{
					out.println("<ol>");
					for(String userName: utenti) {
						out.println("<li><a href='./user.html?name="+userName+"'>"+userName+"</a></li>");					
					}
					out.println("</ol>");
				}
				
				
		} catch (NamingException e) {
			e.printStackTrace();
		}
		out.println("</body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	/*protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("UserManager/remote");
			UserManagerRemote r = (UserManagerRemote) ref;

			request.setAttribute("userNames", r.getUsernames());
			RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/users.jsp");
			dispatcher.forward(request, response); 
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
*/
}